package com.chilly.netty.websocket.action.reconnHeart;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoop;
import io.netty.util.concurrent.ScheduledFuture;

import java.util.concurrent.TimeUnit;

/**
 * 监听器：通过 ChannelFutureListener 来实现客户端的自动重连，有别于断线重连
 * Created by Chilly Cui on 2020/12/28.
 */
public class ListenerClientReconnHeart implements ChannelFutureListener {

    private AppClientReconnHeart appClientReconnHeart = new AppClientReconnHeart("127.0.0.1", 18080);

    //断线重连
    @Override
    public void operationComplete(ChannelFuture channelFuture) throws Exception {
        if (!channelFuture.isSuccess()) {//连接状态不正常
            EventLoop loop = channelFuture.channel().eventLoop();

            ScheduledFuture<?> schedule = loop.schedule(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println("连接状态异常，自动重连>>>>>>>");
                        appClientReconnHeart.run(); //自动重连
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, 5, TimeUnit.SECONDS);
        } else {
            System.out.println("连接状态正常>>>>>>>");
        }

    }
}
